package com.tool.engine.export.write.excel;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;

import java.io.File;
import java.io.IOException;
import java.util.List;

public final class ExportTaskExcelOperation {
    private ExportTaskExcelOperation() {
    }

    public static WriteSheet createExcelSheetByClass(String sheetName, int sheetNo, Class<?> taskType) {
        return EasyExcelFactory.writerSheet(sheetNo, sheetName).head(taskType).build();
    }

    public static void write(List<?> data, ExcelWriter excelWriter, WriteSheet sheet) {
        excelWriter.write(data, sheet);
    }

    public static WriteSheet createExcelSheetByHead(String sheetName, int sheetNo, List<List<String>> head) {
        return EasyExcelFactory.writerSheet(sheetNo, sheetName).head(head).build();
    }

    public static ExcelWriter createExcelWriter(String fileName, String filePath) throws IOException {
        // 文件路径
        String pathName = filePath + File.separator + fileName + ExcelTypeEnum.XLSX.getValue();
        File file = new File(pathName);
        if (!file.exists()) {
            if (file.getParentFile().mkdirs()) {
                boolean newFile = file.createNewFile();
                if (!newFile) {
                    throw new IOException("file create failed pathName:" + filePath);
                }
            }
        }else{
            if(file.delete()){
                boolean newFile = file.createNewFile();
                if (!newFile) {
                    throw new IOException("file create failed pathName:" + filePath);
                }
            }

        }
        return EasyExcelFactory.write(pathName).build();
    }

    public static void finish(ExcelWriter excelWriter) {
        excelWriter.finish();
    }
}
